<?php
/**
 * Created by PhpStorm.
 * User: gqn
 * Date: 2016/3/2
 * Time: 14:53
 */

namespace Admin\Controller;
use Think\Controller;
use Think\Model;

class CouponController extends CommonController{

    static public $treelist = array();

    public static function tree($data,$pid=0,$level=0){
        foreach($data as $key=>$value){
            if($value['pid']==$pid){
                $value['level'] = $level;
                self::$treelist[] = $value;
                unset($data[$key]);
                self::tree($data,$value['category_id'],$level+1);
            }
        }
        return self::$treelist;
    }

    /**
     * 电子券管理
     * @param number
     * @param name
     */
    public function manage(){
        $menu_id=$_GET['id'];
        $jur=jur_str($menu_id,$this->user_id);
        $number = I('get.number');
        $name = I('get.name');
        if($number){
            $maps['volume_number'] = array('like',"%$number%");
        }
        if($name){
            $maps['volume_name'] = array('like',"%$name%");
        }
        $maps['is_delete'] = array('eq',0);
        $maps['end_time'] = array('gt',time());
        $count = M('volume')->where($maps)->count();

        $Page  = new \Think\Page($count,10);// 实例化
        $show  = $Page->show();// 分页显示输出

        $data = M('volume')->order(add_time,desc)->where($maps)->limit($Page->firstRow.','.$Page->listRows)->select();

        foreach($data as $k=>$v){
            $data[$k]['start_time'] = date("Y-m-d",$data[$k]['start_time']);
            $data[$k]['end_time'] = date("Y-m-d",$data[$k]['end_time']);
            $data[$k]['add_time'] = date("Y-m-d H:i:s",$data[$k]['add_time']);
        }
        $this->breadcrumb1='电子券管理';
        $this->breadcrumb2='电子券列表';
        $this->assign('page',$show);
        $this->assign('list',$data);
        $this->assign('update',$jur['is_update']);// 赋值数据集
        $this->assign('delete',$jur['is_delete']);// 赋值数据集
        $this->display();
    }

    /**
     * 添加电子券
     */
    public function addcoupon(){
        if(IS_POST){
            $category =  I('post.category');
            $data['volume_name'] = trim(I('post.volume_name'));
            $data['volume_number'] = date('YmdHis',time());
            $data['total'] = trim(I('post.total'));
            $data['type'] = I('post.type');
            $data['min'] = trim(I('post.min'));
            $data['status'] = I('post.status');
            $data['add_time'] = time();
            $data['start_time'] = strtotime(I('post.start_time'));
            $data['end_time'] = strtotime(I('post.end_time'));
            $sql = "select category_name,category_id from zsf_category where FIND_IN_SET(category_id,'$category')";
            $list = M()->query($sql);
            $tree ='';
            $category_id = '';
            foreach($list as $i=>$k){
                $tree.=$list[$i]['category_name'].'|';
                $category_id.=$list[$i]['category_id'].'|';
            }
            $data['category']=substr($tree,0,-1);
            $data['category_id']=substr($category_id,0,-1);
            $info = M('volume')->add($data);
            if($info){
                echo 1;
                exit;
            }else{
                echo 2;
                exit;
            }
        }
        $this->breadcrumb1='电子券管理';
        $this->breadcrumb2='电子券列表';
        $this->breadcrumb3='添加';
        $this->url1='#';
        $this->url2=U('Coupon/Manage');
        $this->url3='#';

        $this->display();
    }

    /**
     * 发放优惠券
     * @param coupon 优惠券ID
     */

    public function send(){
        $coupon_id = I('post.coupon');
        if(is_array($coupon_id)){
            $couponId = implode(',',$coupon_id);
        }
        $map['volume_id'] = array('in',$couponId);
        $info = M('volume')->field('volume_name,total,status,category,type,min,start_time,end_time')->where($map)->select();
        foreach($info as $key =>$value){
            $info[$key]['start_time'] = date('Y-m-d', $info[$key]['start_time']);
            $info[$key]['end_time'] = date('Y-m-d', $info[$key]['end_time']);
            $info[$key]['coupon']=$couponId;
        }
        $this->breadcrumb1='电子券管理';
        $this->breadcrumb2='电子券列表';
        $this->breadcrumb3='发放';
        $this->url1='#';
        $this->url2=U('Coupon/Manage');
        $this->url3='#';

        $this->assign('send',$info);
        $this->display();
    }

    /**
     * 编辑电子券
     * @param volume_id
     */
    public function editcoupon(){
        if(IS_POST){
            $volume_id = I('post.volume_id');
            $volume_name = trim(I('post.volume_name'));
            $total = trim(I('post.total'));
            $total = $total;
            $min = trim(I('post.min'));
            $min = $min;
            $type = I('post.type');
            $category = I('post.category');
            $status = I('post.status');
            $start_time = strtotime(I('post.start_time'));
            $end_time = strtotime(I('post.end_time'));
            $sql = "select category_name,category_id from zsf_category where FIND_IN_SET(category_id,'$category')";
            $list = M()->query($sql);
            $tree ='';
            $Ids ='';
            foreach($list as $i=>$v){
                $tree.=$list[$i]['category_name'].'|';
                $Ids.=$list[$i]['category_id'].'|';
            }
            $maps['category']= substr($tree,0,-1);
            $maps['category_id'] = substr($Ids,0,-1);
            $maps['volume_name'] = $volume_name;
            $maps['total'] = $total;
            $maps['min'] = $min;
            $maps['type'] = $type;
            $maps['status'] = $status;
            $maps['start_time'] = $start_time;
            $maps['end_time'] = $end_time;
            $whe['volume_id'] = array('eq',$volume_id);
            $VolumeResult = M('volume')->where($whe)->save($maps);
            if($VolumeResult){
                echo 1;
                exit;
            }else {
                echo 2;
                exit;
            }

        }
        $volume_id = I('get.volume_id');
        $volumeData = M('volume')->field('category_id,volume_name,total,type,min,status,start_time,end_time')->where("volume_id = $volume_id")->select();
        foreach($volumeData as $k=>$v){
            $volumeData[$k]['start_time'] = date('Y-m-d H:i:s',$v['start_time']);
            $volumeData[$k]['end_time'] = date('Y-m-d H:i:s',$v['end_time']);
        }
        $rules = explode('|',$volumeData[0][category_id]);
        $data = M('category')->field('category_id,pid as p,category_name')->select();
        $tree = self::tree($data);
        foreach($tree as $i=>$v) {
            $tree[$i]['id'] = $tree[$i]['category_id'];
            $tree[$i]['pid'] = $tree[$i]['p'];
            $tree[$i]['name'] = $tree[$i]['category_name'];
            unset($tree[$i]['category_id']);
            unset($tree[$i]['category_name']);
            unset($tree[$i]['p']);
            unset($tree[$i]['level']);
        }

        foreach($tree as $key =>$value){
            foreach($rules as $v){
                $auth = $value['id'];
                if($auth==$v){
                    if(isset($tree[$key]['children'])&&!empty($tree[$key]['children'])){
                        $children = $tree[$key]['children'];
                        foreach($children as $a => $cv){
                            if($v ==$cv['id'] ){
                                $children['checked'] = true;
                                break;
                            }else{
                                $children['checked'] = false;
                            }
                        }
                    }
                    $tree[$key]['checked']=true;
                    break;
                }else{
                    $tree[$key]['checked']=false;
                }

            }
        }
        $data = list_to_tree($tree);
        $info = json_encode($data);
        $this->breadcrumb1='电子券管理';
        $this->breadcrumb2='电子券列表';
        $this->breadcrumb3='编辑';
        $this->url1='#';
        $this->url2=U('Coupon/Manage');
        $this->url3='#';
        $this->assign('info',$volumeData);
        $this->assign('menuList',$info);
        $this->display();
    }

    /**
     * 分类范围
     */

    public function range()
    {
        $data = M('category')->field('category_id,pid,category_name')->order(array('order' => 'desc'))->select();
        $tree = self::tree($data);
        $count = count($tree);
        for($i=0;$i<$count;$i++){
            $tree[$i]['id'] = $tree[$i]['category_id'];
            $tree[$i]['pId'] = $tree[$i]['pid'];
            $tree[$i]['name'] = $tree[$i]['category_name'];
            unset($tree[$i]['category_id']);
            unset($tree[$i]['category_name']);
            unset($tree[$i]['pid']);
            unset($tree[$i]['level']);
        }
        echo json_encode($tree);
    }

    /**
     * 电子券详情
     * @param volume_id 电子券详情
     */
    public function detail(){
        $id = I('get.volume_id');

        $data = M('volume')->where("volume_id = $id")->select();
        $data[0]['start_time'] = date('Y-m-d',$data[0]['start_time']);
        $data[0]['end_time'] = date('Y-m-d',$data[0]['end_time']);

        $this->breadcrumb1='电子券管理';
        $this->breadcrumb2='电子券列表';
        $this->breadcrumb3='详情';
        $this->url2=U('Coupon/Manage');
        $this->assign('detail',$data);
        $this->display();
    }

    /**
     * 发放优惠券
     */
    public function sendcoupon(){
        $couponIds = I('get.coupon');
        $cup['volume_id'] = array("exp","in($couponIds)");
        $cup['status'] = array('eq',0);
        $useCoupon = M('volume')->where($cup)->select();
        if($useCoupon){
            echo 2;
            exit;
        }
        unset($cup['status']);
        $coupon = M('volume')->where($cup)->select();

        $userIds = I('get.user');
        $userIds = implode(',',$userIds);
        $map['user_id'] = array('exp',"in($userIds)");
        $usr = M('user')->field('user_id')->where($map)->select();
        foreach($usr as $key=>$value){
            foreach($coupon as $k=>$v){
                $data['user_id'] = $usr[$key]['user_id'];
                $data['start_time'] = $coupon[$k]['start_time'];
                $data['end_time'] = $coupon[$k]['end_time'];
                $data['add_time'] = time();
                $data['volume_id'] = $coupon[$k]['volume_id'];
                $data['volume_name'] = $coupon[$k]['volume_name'];
                $data['total'] = $coupon[$k]['total'];
                $data['category'] = $coupon[$k]['category'];
                $data['category_id'] = $coupon[$k]['category_id'];
                $data['volume_name'] = $coupon[$k]['volume_name'];
                $data['type'] = $coupon[$k]['type'];
                $data['min'] = $coupon[$k]['min'];
                $data['get_scene'] = '后台发放';
                M('volume_list')->add($data);
            }
        }
        echo 1;
        exit;
    }

    /**
     * 获取用户信息
     */

    public function getUserInfo(){
        $name = I('post.name');
        $phone = I('post.phone');
        $pageIndex = I('post.pageIndex',1);
        $pageCount = I('post.pageCount',10);
        if($name!='') {
            $maps['user_name'] = array('like', "%$name%");
        }
        if($phone!='') {
            $maps['phone'] = array('like',"%$phone%");
        }
        $counts = M('user')->where($maps)->count();
        $pages = ceil($counts/$pageCount);
        $limit = ($pageIndex-1)*$pageCount;
        if($counts){
            $user = array();
            $user['data'] = M('user')->field('user_id,user_name,phone')->where($maps)->limit($limit.','.$pageCount)->select();
            $user['pages'] = $pages;
            $user['pageIndex'] = $pageIndex;
            echo json_encode($user);
        }
    }

    /**
     * 电子券使用统计
     * @param name 电子券名称
     * @param number 电子券号
     */
    public function CouponUseCount(){
        $name = I('get.name'); //电子券名称
        $number = I('get.number');//电子券号
        if($name){
            $maps['volume_name'] = array('like',"%$name%");
        }
        if($number){
            $maps['volume_number'] = array('like',"%$number%");
        }
        $count = M('volume')->field('volume_id,volume_number,volume_name,total,category')
            ->where($maps)->count();
        $Page  = new \Think\Page($count,10);// 实例化
        $show  = $Page->show();// 分页显示输出
        $data = M('volume')->field('volume_id,volume_number,volume_name,total,category')
                ->where($maps)->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach($data as $k=>$v){
            $getResult = M('volume_list')->field('count(*) as count')->where("volume_id = ".$v['volume_id'])->find();
            $data[$k]['get_count'] = $getResult['count'];
            $useResult = M('volume_list')->field('count(*) as count')->where("volume_id = ".$v['volume_id'] ." and status = 2")->find();
            $data[$k]['use_count'] = $useResult['count'];
        }

        $this->breadcrumb1='电子券管理';
        $this->breadcrumb2='电子券使用统计';
        $this->assign('page',$show);
        $this->assign('Coupon',$data);
        $this->display('usecount');
    }

    /**
     * 过期电子券
     * @param name 电子券名称
     * @param number 电子券号
     */
    public function CouponInUse(){
        $name = I('get.name'); //电子券名称
        $number = I('get.number');//电子券号
        $menu_id=$_GET['id'];
        $jur=jur_str($menu_id,$this->user_id);
        if($name){
            $maps['volume_name'] = array('like',"%$name%");
        }
        if($number){
            $maps['volume_number'] = array('like',"%$number%");
        }
        $maps['is_delete'] = array('neq','1');
        $maps['end_time'] = array('lt',time());
        $maps['status'] = array('eq',0);
        $count = M('volume')->field('volume_id,volume_number,volume_name,total,category,type,min,start_time,end_time,add_time')
            ->where($maps)->count();
        $Page  = new \Think\Page($count,10);// 实例化
        $show  = $Page->show();// 分页显示输出
        $data = M('volume')->field('volume_id,volume_number,volume_name,total,category,type,min,start_time,end_time,add_time')
                ->where($maps)->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach($data as $k=>$v){
            $data[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            $data[$k]['start_time'] = date('Y-m-d',$v['start_time']);
            $data[$k]['end_time'] = date('Y-m-d',$v['end_time']);
            $getResult = M('volume_list')->field('count(*) as count')->where("volume_id = ".$v['volume_id'])->find();
            $data[$k]['get_count'] = $getResult['count'];
            $useResult = M('volume_list')->field('count(*) as count')->where("volume_id = ".$v['volume_id'] ." and status = 2")->find();
            $data[$k]['use_count'] = $useResult['count'];
        }
        $this->breadcrumb1='电子券管理';
        $this->breadcrumb2='过期电子券';
        $this->assign('page',$show);
        $this->assign('Coupon',$data);
        $this->assign('update',$jur['is_update']);// 赋值数据集
        $this->assign('delete',$jur['is_delete']);// 赋值数据集
        $this->display('usedcoupon');
    }

    /**
     * 电子券使用情况
     * @param number 电子券号
     * @param name 电子券名称
     * @param user_name 用户姓名
     * @param user_phone 用户电话
     */
    public function CouponUseInfo(){
        $number = I('get.number');
        $name = I('get.name');
        $user_name = I('get.user_name');
        $user_phone = I('get.user_phone');
        if($number){
            $maps['vl.volume_number'] = array('like',"%$number%");
        }
        if($name){
            $maps['vo.volume_name'] = array('like',"%$name%");
        }
        if($user_name){
            $maps['usr.user_name'] = array('like',"%$user_name%");
        }
        if($user_phone){
            $maps['usr.phone'] = array('like',"%$user_phone%");
        }

        $count = M()->table('zsf_volume_list vo')->field('vo.*,vl.volume_number,usr.phone,usr.user_name')
            ->join("LEFT JOIN zsf_volume vl on vl.volume_id = vo.volume_id")
            ->join("LEFT JOIN zsf_user usr on vo.user_id = usr.user_id")
            ->where($maps)->count();
        $Page  = new \Think\Page($count,10);// 实例化
        $show  = $Page->show();// 分页显示输出

        $data = M()->table('zsf_volume_list vo')->field('vo.*,vl.volume_number,usr.phone,usr.user_name')
                ->join("LEFT JOIN zsf_volume vl on vl.volume_id = vo.volume_id")
                ->join("LEFT JOIN zsf_user usr on vo.user_id = usr.user_id")
                ->where($maps)
                ->limit($Page->firstRow.','.$Page->listRows)
                ->select();
        foreach($data as $k=>$v){
            $data[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            if(!empty($v['use_time'])){
                $data[$k]['use_time'] = date('Y-m-d H:i:s',$v['use_time']);
            }else{
                $data[$k]['use_time'] = "未使用";
            }
            $data[$k]['start_time'] = date('Ymd',$v['start_time']);
            $data[$k]['end_time'] = date('Ymd',$v['end_time']);
            if($v['status'] =='2'){
                $orderWhere['volume_list_id'] = array('eq',$v['volume_list_id']);
                $orderWhere['user_id'] = array('eq',$v['user_id']);
                $orderResult = M('repair_order')->field('repair_order_id,repair_order_num_alias,category_name')->where($orderWhere)->find();
                $data[$k]['repair_order_num'] = $orderResult['repair_order_num_alias'];
                $data[$k]['category_name'] = $orderResult['category_name'];
                $data[$k]['repair_order_id'] = $orderResult['repair_order_id'];
            }

        }
        $this->breadcrumb1='电子券管理';
        $this->breadcrumb2='电子券使用情况';
        $this->assign('page',$show);
        $this->assign('Coupon',$data);
        $this->display('CouponUseInfo');

    }

    /**
     * 删除优惠券
     * @info 逻辑删除
     */
    public function del(){
        $id = I('post.Del');
        $map['volume_id'] = array('in',$id);
        $inf['is_delete'] = '1';
        $data = M('volume')->where($map)->save($inf);
        if($data){
            echo 1;
            exit;
        }else {
            echo 2;
            exit;
        }

    }

    /**
     * 电子券领取详情
     * @param coupon_id
     * @scene get
     */
    public function GetCouponSendInfo(){
        $coupon_id = I('get.coupon_id');
        $scene = I('get.scene');

        $data = M('volume')->where("volume_id = $coupon_id")->select();
        foreach($data as $k=>$v){
            $data[$k]['start_time'] = date('Y-m-d',$v['start_time']);
            $data[$k]['end_time'] = date('Y-m-d',$v['end_time']);
            $data[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            if($v['type']=='1'){
                $data[$k]['type'] = '代金券';
            }else{
                $data[$k]['type'] = '现金券';
            }
        }
        if($scene == 'get'){
            $counts = M()->table('zsf_volume_list vol')->field('vol.get_scene,vol.use_scene,vol.add_time,usr.user_name,usr.phone')
                ->join("LEFT JOIN zsf_user usr on usr.user_id = vol.user_id")
                ->where("vol.volume_id = $coupon_id")->count();
            $Page  = new \Think\Page($counts,10);// 实例化
            $show  = $Page->show();// 分页显示输出

            $info = M()->table('zsf_volume_list vol')->field('vol.get_scene,vol.use_scene,vol.add_time,usr.user_name,usr.phone')
                    ->join("LEFT JOIN zsf_user usr on usr.user_id = vol.user_id")
                    ->where("vol.volume_id = $coupon_id")->limit($Page->firstRow.','.$Page->listRows)->select();
        }elseif($scene == 'use'){
            $counts = M()->table('zsf_volume_list vol')->field('vol.get_scene,vol.use_scene,vol.add_time,usr.user_name,usr.phone')
                ->join("LEFT JOIN zsf_user usr on usr.user_id = vol.user_id")
                ->where("vol.volume_id = $coupon_id and vol.status = 2")->count();
            $Page  = new \Think\Page($counts,10);// 实例化
            $show  = $Page->show();// 分页显示输出
            $info = M()->table('zsf_volume_list vol')->field('vol.get_scene,vol.use_scene,vol.add_time,usr.user_name,usr.phone')
                ->join("LEFT JOIN zsf_user usr on usr.user_id = vol.user_id")
                ->where("vol.volume_id = $coupon_id and vol.status = 2")->limit($Page->firstRow.','.$Page->listRows)->select();
        }
        foreach($info as $k=>$v){
            $info[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
        }

        $this->breadcrumb1='电子券管理';
        $this->breadcrumb2='电子券使用统计';
        $this->breadcrumb3='电子券领取详情';
        $this->url2=U("Coupon/CouponUseCount");
        $this->assign('self',$data);
        $this->assign('coupon',$info);
        $this->assign('page',$show);
        $this->display('getcouponinfo');

    }

    /**
     * 电子券领取规则
     */
    public function GetCouponRule(){
        $this->breadcrumb1='电子券管理';
        $this->breadcrumb2='电子券领取规则';
        $this->display();
    }



}